﻿(function($) {
    $.fn.labelize = function() {
        return this.each(function() {

            var $input = $(this);
            var $label = $(this).prev('label');

            if(!$input.val())
                $input.val($label.text());


            //We need to know if input is of type password.
            if ($input.attr('type') == 'password') {
                $input = changeInputType($input, 'text');
                $input.addClass('password');
            }

            $input.focus(function() {
                if ($input.val() == $label.text()) {
                    if ($input.hasClass('password')) {
                        $input = changeInputType($input, 'password');
                        $input.focus();
                    }
                    $input.val('').addClass('edited');
                }
            });
            $input.blur(function() {
                if (!$input.val()) {
                    $input.val($label.text());
                    $input.removeClass('edited');
                }
                else {
                    $input.addClass('edited');
                }
            });
            //}
        });
        function changeInputType($input, value) {
            //Manipulation of input type attribute is not allowed. Therefore we need to replace the input box.
            var $new = $('<input type="' + value + '" />')
            $new.val($input.val()).attr('class', $input.attr('class')).attr('id', $input.attr('id')).attr('name', $input.attr('name'));
            $input.replaceWith($new);
            return $new;
        }
    }
})(jQuery);